import numpy as np
import talib
class KDJ:
    def __init__(self, options):
        self.logger = options['logger']

    def getStatus(self, data, fastkPeriod=9, slowkPeriod=3, slowdPeriod=3):
        ''' 获取KDJ买卖状态 '''
        indicators = {}
        length = len(data)
        # 计算kd指标
        high_prices = np.array([v[2] for v in data], dtype=float)
        low_prices = np.array([v[3] for v in data], dtype=float)
        close_prices = np.array([v[4] for v in data], dtype=float)
        indicators['k'], indicators['d'] = talib.STOCH(high_prices, low_prices, close_prices,
                                                       fastk_period=fastkPeriod,
                                                       slowk_period=slowkPeriod,
                                                       slowd_period=slowdPeriod)
        indicators['j'] = 3 * indicators['k'] - 2 * indicators['d']
        jlast_01 = indicators['j'][length-1]
        klast_01 = indicators['k'][length-1]
        dlast_01 = indicators['d'][length-1]
        jlast_02 = indicators['j'][length-2]
        klast_02 = indicators['k'][length-2]
        dlast_02 = indicators['d'][length-2]
        iscode_01 = float(jlast_01) > float(
            klast_01) and float(jlast_01) > float(dlast_01)
        iscode_02 = float(jlast_02) > float(
            klast_02) and float(jlast_02) > float(dlast_02)
        kdj_max_100 = float(indicators['j'][length-1]) > 95
        message = 'iscode_01:{iscode_01},iscode_02:{iscode_02},kdj_max_100:{kdj_max_100}'.format(
            iscode_01=iscode_01, iscode_02=iscode_02, kdj_max_100=kdj_max_100)
        self.logger.info(message)
        if iscode_01 is True and iscode_02 is True and kdj_max_100 is True:
            message = 'kdj 判断上升 属于可购买'
            flag = True
        else:
            message = 'kdj 判断非上升 属于不可购买'
            flag = False

        self.logger.info(message)
        return flag
